import request from '@/utils/request';

// 测试Redis连接
export function ping() {
  return request({
    url: '/redis/ping',
    method: 'get'
  });
}

// 设置缓存
export function setCache(key, value) {
  return request({
    url: '/redis/set',
    method: 'post',
    params: { key, value }
  });
}

// 获取缓存
export function getCache(key) {
  return request({
    url: '/redis/get',
    method: 'get',
    params: { key }
  });
}

// 删除缓存
export function deleteCache(key) {
  return request({
    url: '/redis/delete',
    method: 'delete',
    params: { key }
  });
}

// 获取Redis集群信息
export function getRedisInfo() {
  return request({
    url: '/redis/info',
    method: 'get',
    // 禁用缓存，确保每次都获取最新数据
    headers: {
      'Cache-Control': 'no-cache',
      'Pragma': 'no-cache'
    }
  });
}

// 设置字符串缓存
export function setStringCache(key, value) {
  return request({
    url: '/redis/setString',
    method: 'post',
    params: { key, value }
  });
}

// 获取字符串缓存
export function getStringCache(key, db = 0) {
  return request({
    url: '/redis/getString',
    method: 'get',
    params: { key, db }
  });
}

// 获取所有缓存键 - 支持分页
export function getCacheKeys(pattern = '*', db = 0, page = 1, size = 50) {
  return request({
    url: '/redis/keys',
    method: 'get',
    params: { pattern, db, page, size }
  });
}

// 导出缓存数据
export function exportCache(pattern = '*', db = 0, format = 'json') {
  return request({
    url: '/redis/export',
    method: 'get',
    params: { pattern, db, format }
  });
}

// 导入缓存数据
export function importCache(data, db = 0) {
  return request({
    url: '/redis/import',
    method: 'post',
    params: { db },
    data: { data }
  });
}

// 优化版导出缓存 - 支持多种导出方式
export function exportCacheOptimized(pattern = '*', db = 0, method = 'auto') {
  return request({
    url: '/redis/export/optimized',
    method: 'get',
    params: { pattern, db, method }
  });
}

// 分批导出缓存
export function exportCacheBatch(batch = 1, pattern = '*', db = 0, batchSize = 5000) {
  return request({
    url: '/redis/export/batch',
    method: 'get',
    params: { batch, pattern, db, batchSize }
  });
}

// 流式导出缓存（直接下载文件）
export function downloadCacheStream(pattern = '*', db = 0) {
  const params = new URLSearchParams({ pattern, db, method: 'stream' });
  const url = `/api/redis/export/optimized?${params.toString()}`;
  
  // 创建隐藏的下载链接
  const link = document.createElement('a');
  link.href = url;
  link.download = `redis_export_db${db}_${Date.now()}.json`;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}
